package com.taokatao.cardmee.business.cardcode;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.taokatao.cardmee.ActivityCollector;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.BusEvent;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespInfo;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.CardShareInfo;
import com.taokatao.cardmee.business.MainActivity;
import com.taokatao.cardmee.business.cardcrud.CardInfoEditActivity;
import com.taokatao.cardmee.business.carddetail.CardDetailActivity;
import com.taokatao.cardmee.common.widget.ShareDialog;
import com.taokatao.cardmee.common.widget.SheetDialog;
import com.taokatao.cardmee.common.widget.TitleLayout;
import com.taokatao.cardmee.common.widget.TouchBackLayout;
import com.taokatao.cardmee.db.model.Card;
import com.taokatao.cardmee.R;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class CardCodeActivity extends BaseActivity implements CardCodeTabStrip.Callback, TitleLayout.Callback {

    @BindView(R.id.l_title) TitleLayout lTitle;
    @BindView(R.id.v_tab_strip) CardCodeTabStrip vTabStrip;
    @BindView(R.id.v_pager) ViewPager viewPager;
    private CardDetailInfoPagerAdapter adapter;

    @BindView(R.id.i_icon) ImageView iIcon;
    @BindView(R.id.v_code_background) View vCodeBackground;

    private SheetDialog dlgSheet;
    private int styleColor;
    private boolean isCustomMode;
    private Card c;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_code);
        ButterKnife.bind(this);

        if (layTouchToBack != null)
            layTouchToBack.setOnTouchCallback(new TouchBackLayout.Callback() {
                @Override
                public void onTouchBack(View view) {
                    if (viewPager.getCurrentItem() == 0) {
                        if (ActivityCollector.size() > 1) {
                            finish();
                        }
                    }
                }
            });

        c = (Card) getIntent().getSerializableExtra("extra_card");
        isCustomMode = C.settings.BUSINESS_OTHER_ID == c.getBusinessId();

        vTabStrip.setCallback(this);
        vTabStrip.setData(c);

        lTitle.setCallback(this);


        if (isCustomMode) {
            styleColor = 0xFF4C4C4C;
            if (!TextUtils.isEmpty(c.getBuPic())) {
                Glide.with(this).load(c.getBuPic()).centerCrop()
                        .bitmapTransform(App.i().getCropCircleTransformation()).into(iIcon);
            }
        } else {
            if (!TextUtils.isEmpty(c.getBackColor()) && c.getBackColor().length() == 7 && c.getBackColor().startsWith("#")) {
                styleColor = Color.parseColor(c.getBackColor());
            } else {
                styleColor = 0xFF4C4C4C;
            }
//            if (!TextUtils.isEmpty(c.getMCardIcon())) {
                Glide.with(this).load(c.getMCardIcon()).centerCrop().into(iIcon);
//            }
        }



        vCodeBackground.setBackgroundColor(styleColor);
        lTitle.setBackgroundColor(styleColor);
        lTitle.setMenuIcon(lTitle.isDarkBackgroundColor() ? R.mipmap.card_menu_white : R.mipmap.card_menu_black);

        viewPager.setAdapter(adapter = new CardDetailInfoPagerAdapter(c));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                if (adapter.menuList.size() > position) {
                    String currTab = adapter.menuList.get(position);
                    switch (currTab) {
                        case CardDetailInfoPagerAdapter.CONTENT_SCAN:
                            Utils.onMobEvent(CardCodeActivity.this, "entryCardPageOfCardDetails");
                            vTabStrip.clickTab(CardCodeTabStrip.Menu.Code, false);
                            break;
                        case CardDetailInfoPagerAdapter.CONTENT_I_FRONT:
                            Utils.onMobEvent(CardCodeActivity.this, "entryPositivePageOfCardDetails");
                            vTabStrip.clickTab(CardCodeTabStrip.Menu.IFront, false);
                            break;
                        case CardDetailInfoPagerAdapter.CONTENT_I_BACK:
                            Utils.onMobEvent(CardCodeActivity.this, "entryNegativePageOfCardDetails");
                            vTabStrip.clickTab(CardCodeTabStrip.Menu.IBack, false);
                            break;
                        case CardDetailInfoPagerAdapter.CONTENT_OTHER:
                            Utils.onMobEvent(CardCodeActivity.this, "entryMorePageOfCardDetails");
                            vTabStrip.clickTab(CardCodeTabStrip.Menu.OTHER, false);
                            break;
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        requestUpdateCardUseCount();
    }

    @Override
    public void onMenuClick(TitleLayout lTitle, String flag) {
        Utils.onMobEvent(this, "clickEditButtonOfCardDetails");
        showSheetDialog();
    }

    private void showSheetDialog() {
        if (dlgSheet == null) {
            SheetDialog.Builder builder = new SheetDialog.Builder(this);
            // 是收藏卡
            if (TextUtils.equals(c.getIsMyCard(), Card.STATUS_FAVORITE_CARD)) {
                builder.addMenu("放弃收藏", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Utils.onMobEvent(CardCodeActivity.this, "clickGiveupCollectionMenuOfCardDetails");
                        requestCancelStarCard();
                    }
                });
            }
            // 是最普通的卡
            else if (TextUtils.equals(c.getIsMyCard(), Card.STATUS_MY_CARD) && c.getSid() == null) {
                builder.addMenu("编辑", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        Utils.onMobEvent(CardCodeActivity.this, "clickEditMenuOfCardDetails");
                        Intent intent = new Intent(CardCodeActivity.this, CardInfoEditActivity.class);
                        intent.putExtra("extra_card", App.i().getGson().toJson(c));
                        startActivity(intent);
                    }
                });
            }
            // 其它的 分店卡或者通兑卡
            else {
                builder.addMenu("删除会员卡", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        requestDeleteCard();
                    }
                });
            }

            builder.addMenu("分享给好友", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                    // 先提示 免责声明
                    new com.taokatao.cardmee.common.widget.AlertDialog.Builder(CardCodeActivity.this)
                            .setMessage("请谨慎分享会员卡，以免造成损失，是否继续分享？")
                            .setTitle("提示")
                            .setPositiveButton("继续", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();

                                    Utils.onMobEvent(CardCodeActivity.this, "clickShareMenuOfCardDetails", new String[]{"click"},
                                            new String[]{c.getBusinessId() + "_" + c.getMCardId()});
                                    new ShareDialog.Builder(CardCodeActivity.this)
                                            .setCallback(new ShareDialog.OnShareClickListener() {
                                                @Override
                                                public void onPlatformClick(Dialog dialog, SHARE_MEDIA platform) {
                                                    requestObtainCardShareUrl(platform);
                                                    dialog.dismiss();
                                                }
                                            }).create().show();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create().show();
                }
            });

            dlgSheet = builder.create();
        }
        dlgSheet.show();
    }

    private void requestDeleteCard() {
        ApiManager.i().deleteCard(this, App.i().getCurrUser().getUuid(), c.getMCardId(),c.getIsMyCard(), new SubscriberAdapter<RespWrapper<RespInfo>>() {
            @Override
            public void onNext(RespWrapper<RespInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    Utils.postMainThreadBusEvent(BusEvent.CARD_DELETE, c);
                    ActivityCollector.finishAllExcept(MainActivity.class);
                }
            }
        }.showProgress(this));
    }

    private void requestObtainCardShareUrl(final SHARE_MEDIA platform) {
        ApiManager.i().obtainCardShareUrl(this, App.i().getCurrUser().getUuid(), c.getMCardId(), new SubscriberAdapter<RespWrapper<CardShareInfo>>() {
            @Override
            public void onNext(RespWrapper<CardShareInfo> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    String mName = "我";
                    if (App.i().getCurrUser() != null && !TextUtils.isEmpty(App.i().getCurrUser().getUserName())) {
                        mName = App.i().getCurrUser().getUserName();
                    }
                    String mCardName = isCustomMode ? c.getAnotherBusiness() : c.getBusinessName();
                    String mCardGrade = "会员卡";
                    if (!TextUtils.isEmpty(c.getGradeName()) && !TextUtils.equals("普通卡", c.getGradeName())) {
                        mCardGrade = c.getGradeName();
                    }
                    String mTitle = String.format("%s分享的%s%s", mName, mCardName, mCardGrade);

                    UMImage image = new UMImage(CardCodeActivity.this, isCustomMode ? c.getBuPic() : c.getMCardIcon());
                    new ShareAction(CardCodeActivity.this).setPlatform(platform)
                            .withText("不准外传！\n ▍▎▏▏▎▏▏▎▍")
                            .withTitle(mTitle)
                            .withTargetUrl(o.decode(CardShareInfo.class).shareMcardUrl)
                            .withMedia(image)
                            .setCallback(new UMShareListener() {
                                @Override
                                public void onResult(SHARE_MEDIA share_media) {
                                    Utils.onMobEvent(CardCodeActivity.this, "shareCardSucc", new String[]{"success"},
                                            new String[]{c.getBusinessId() + "_" + c.getMCardId()});
                                    Utils.showToast("分享成功");
                                }

                                @Override
                                public void onError(SHARE_MEDIA share_media, Throwable throwable) {
                                    Utils.onMobEvent(CardCodeActivity.this, "shareCardFail", new String[]{"fail"},
                                            new String[]{c.getBusinessId() + "_" + c.getMCardId()});
                                    Utils.showToast("分享失败");
                                }

                                @Override
                                public void onCancel(SHARE_MEDIA share_media) {
                                    Utils.onMobEvent(CardCodeActivity.this, "shareCardFail", new String[]{"fail"},
                                            new String[]{c.getBusinessId() + "_" + c.getMCardId()});
                                    Utils.showToast("分享取消");
                                }
                            }).share();
                }
            }
        }.showProgress(this));
    }

    private void requestCancelStarCard() {
        if (App.i().getCurrUser() != null) {
            ApiManager.i().cancelStarCard(this, App.i().getCurrUser().getUuid(), c.getMCardId(), new SubscriberAdapter<RespWrapper<RespInfo>>() {
                @Override
                public void onNext(RespWrapper<RespInfo> o) {
                    super.onNext(o);
                    if (o.code == C.http.RESULT_CODE_SUCCESS) {
                        Utils.postMainThreadBusEvent(BusEvent.CARD_DELETE, c);
                        finish();
                    }
                }
            }.showProgress(this));
        }
    }

    @Override
    public void onTabStripClick(int selected) {


        viewPager.setCurrentItem(selected - 1);
    }

    private void requestUpdateCardUseCount() {
        ApiManager.i().updateCardUseCount(this, c.getMCardId(), 2, new SubscriberAdapter<RespWrapper<RespInfo>>() {
        }.errorToast(false));
    }

    private static class CardDetailInfoPagerAdapter extends PagerAdapter {
        private static final String CONTENT_SCAN = "scan";
        private static final String CONTENT_I_FRONT = "i_front";
        private static final String CONTENT_I_BACK = "i_back";
        private static final String CONTENT_OTHER = "other";
        private final List<String> menuList = new ArrayList<>();
        private final Map<String, ICardDetailInfoLayout> contents = new HashMap<>();
        private final Card c;

        CardDetailInfoPagerAdapter(Card card) {
            Utils.logd("CardCodActivity info prepare [%s]", card.toString());
            menuList.clear();
            c = card;
            if (c != null) {
                if (!TextUtils.isEmpty(c.getMCardNo())
                        || !TextUtils.isEmpty(c.getCardUser()) || !TextUtils.isEmpty(c.getCardTel())) {
                    menuList.add(CONTENT_SCAN);
                    Utils.logd("CardCodActivity info add SCAN");
                }
                if (!TextUtils.isEmpty(c.getPositiveIcon())) {
                    menuList.add(CONTENT_I_FRONT);
                    Utils.logd("CardCodActivity info add I_FRONT");
                }
                if (!TextUtils.isEmpty(c.getBackIcon())) {
                    menuList.add(CONTENT_I_BACK);
                    Utils.logd("CardCodActivity info add BACK");
                }
                menuList.add(CONTENT_OTHER);
            }
        }

        @Override
        public int getCount() {
            return menuList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (menuList.size() > position) {
                final String tab = menuList.get(position);
                ICardDetailInfoLayout layCardContent = contents.get(tab);
                if (layCardContent != null) {
                    container.removeView(layCardContent);
                    contents.remove(tab);
                }
            }
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ICardDetailInfoLayout layCardContent = null;
            if (menuList.size() > position) {
                final String tab = menuList.get(position);
                switch (tab) {
                    case CONTENT_SCAN:
                        layCardContent = new CardCodePreviewLayout(container.getContext());
                        break;
                    case CONTENT_I_FRONT:
                        layCardContent = new CardCodeIFrontLayout(container.getContext());
                        break;
                    case CONTENT_I_BACK:
                        layCardContent = new CardCodeIBackLayout(container.getContext());
                        break;
                    case CONTENT_OTHER:
                        layCardContent = new CardCodeOtherLayout(container.getContext());
                        break;
                }
                if (layCardContent != null) {
                    layCardContent.prepareData(c);
                    container.addView(layCardContent);
                    contents.put(tab, layCardContent);
                }
            }
            return layCardContent;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.screenBrightness = 0.85f;
        getWindow().setAttributes(layoutParams);
    }

    @Override
    protected void onPause() {
        super.onPause();
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.screenBrightness = -1;
        getWindow().setAttributes(layoutParams);
    }

    @Override
    public void onBackPressed() {
        supportFinishAfterTransition();
    }
}
